package com.zff.rental.service.apartment;


import com.zff.rental.common.BusinessException;
import com.zff.rental.entity.apartment.ApartmentManager;
import com.zff.rental.repository.apartment.ApartmentManagerRepository;
import com.zff.rental.service.AdminService;
import com.zff.rental.tools.UserContextHolder;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

/**
 * @author HCY
 */
@Service
public class ApartmentPermissionServer {
    /**
     * 公寓权限管理
     */
    @Resource
    private ApartmentManagerRepository apartmentManagerRepository;

    @Resource
    private AdminService adminService;

    /**
     * 检查公寓权限权限
     *
     * @param apartmentId 公寓Id
     */
    public void checkPermission(Long apartmentId) throws BusinessException {
        Long userId = UserContextHolder.getUserId();
        if (adminService.isAdmin(userId)) {
            // 超级管理员，可随意操作
            return;
        }
        checkPermission(apartmentId, userId);
    }

    public void checkPermission(Long apartmentId, Long userId) throws BusinessException {
        ApartmentManager apartmentManager = apartmentManagerRepository.findById(new ApartmentManager.MId(apartmentId, userId))
                .orElseThrow(() -> new BusinessException("您没有权限操作该公寓"));

        if (!apartmentManager.isAdmin() && !apartmentManager.isButler()) {
            throw new BusinessException("您没有权限操作该公寓");
        }
    }
}
